﻿using Aspose.Cells.Tables;
using CRMGateway;
using CRMModel;
using FRMS;
using FRMS.BUS;
using FRMS.DAL;
using FRMS.Model;
using FRMS_N71SP.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace FRMS_N71SP.BUS
{
    public class N71SPDeviceBUS
    {
        public bool LoginDevice(string deviceno, string deviceip, string username, string password, int forcelogin)
        {
            try
            {
                N71SPLoginInfo n71SPLoginInfo = new N71SPLoginInfo();
                N71SPLoginInfoData n71SPLoginInfoData = new N71SPLoginInfoData();
                n71SPLoginInfoData.UserName = username;
                n71SPLoginInfoData.Password = password;
                n71SPLoginInfoData.ForceLogin = forcelogin;
                n71SPLoginInfo.ParamsInfo = n71SPLoginInfoData;

                string data = JsonConvert.SerializeObject(n71SPLoginInfo).Replace("ParamsInfo", "params");
                string re = N71SPHttpClientPost("http://" + deviceip + "/api/system/login", data);
                PersonReturnData PicLssueinfoReturn = JsonConvert.DeserializeObject<PersonReturnData>(re);

                if (PicLssueinfoReturn != null && PicLssueinfoReturn.result == 0 && PicLssueinfoReturn.method == "login")
                {
                    N71SPCallBackInfo n71SPCallBackInfo = new N71SPCallBackInfo();
                    string addr_ip = AppSettingsHelper.Configuration["ArrangeIP"];
                    n71SPCallBackInfo.HeartUrl = string.Format("http://{0}/api/DeviceInteraction/N71SPHeartbeat", addr_ip);
                    n71SPCallBackInfo.RecordUrl = string.Format("http://{0}/api/DeviceInteraction/N71SPRecord", addr_ip);
                    n71SPCallBackInfo.HeartTime = 1;
                    n71SPCallBackInfo.UploadType = "Real";

                    string callback_data = JsonConvert.SerializeObject(n71SPCallBackInfo);
                    string callback_re = N71SPHttpClientPost("http://" + deviceip + "/api/system/setCallBack", callback_data);
                    PersonReturnData callback_Return = JsonConvert.DeserializeObject<PersonReturnData>(callback_re);
                    if (callback_Return != null && callback_Return.result == 0 && callback_Return.method == "setCallBack")
                    {
                        N71SPLoginReturn n71SPLoginReturn = JsonConvert.DeserializeObject<N71SPLoginReturn>(PicLssueinfoReturn.Params.ToString());
                        DeviceDAL deviceDAL = new DeviceDAL();
                        bool token_result = deviceDAL.UpdateToken(n71SPLoginReturn.Token, deviceip);
                        if (token_result)
                        {
                            DataDownLoad.UpdateRegisterFlag(deviceno, true);
                            if (DataDownLoad.device_dic.ContainsKey(deviceno))
                            {
                                DataDownLoad.device_dic.Remove(deviceno);
                            }
                            DataDownLoad.device_dic.Add(deviceno, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public string N71SPHttpClientPost(string url, string datajson)
        {
            HttpClient httpClient = new HttpClient();//http对象
            //表头参数
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //转为链接需要的格式
            var content = new StringContent(datajson, Encoding.UTF8, "application/json");
            //请求
            HttpResponseMessage response = httpClient.PostAsync(url, content).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    return t.Result;
                }
            }
            return "";
        }

        public ResponseMessage SyncRecord(string starttime, string endtime)
        {
            ResponseMessage response = new ResponseMessage();
            try
            {
                DeviceDAL deviceDAL = new DeviceDAL();
                List<DeviceInfo> list = deviceDAL.QueryN71SPOffLine("在线");
                if (list != null && list.Count > 0)
                {
                    foreach (DeviceInfo deviceInfo in list)
                    {
                        N71SPDateSync(deviceInfo);
                        N71SPQueryRecord(deviceInfo, starttime, endtime);
                    }
                }

            }
            catch (Exception ex)
            {
                response.errcode = 1;
                response.errmsg = "同步考勤记录异常" + ex.ToString();
            }
            return response;
        }

        public string N71SPQueryRecord(DeviceInfo deviceInfo, string starttime, string endtime)
        {
            try
            {
                CheckInOutInfo checkInOutInfo = new CheckInOutInfo();
                checkInOutInfo.endtime = Convert.ToDateTime(endtime).AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");
                checkInOutInfo.devideid = deviceInfo.DeviceNO;
                checkInOutInfo.starttime = Convert.ToDateTime(starttime).ToString("yyyy-MM-dd HH:mm:ss");
                AttendanceDAL attendanceDAL = new AttendanceDAL();
                List<AttendanceInfo> attendanceInfos = attendanceDAL.QueryCheckInOut(checkInOutInfo);
                int offset = 0;
                int count = -1;
                int total = 0;
                int lastoffset = 0;

                while (lastoffset + count < total)
                {
                    NS71RecordReturn infoReturn = QueryN72SP(deviceInfo, starttime, endtime, offset, out count, out total);
                    if (count == 0 && total == 0)
                    {
                        break;
                    }
                    if (infoReturn != null && infoReturn.Params != null && infoReturn.Params.RecordCount > 0)
                    {
                        lastoffset = offset;
                        offset += 100;
                        VoucherDAL voucherDAL = new VoucherDAL();
                        DeviceDAL deviceDAL = new DeviceDAL();

                        if (infoReturn.Params.Records != null && infoReturn.Params.Records.Count > 0)
                        {
                            List<RecordList> recordLists = infoReturn.Params.Records.FindAll(delegate (RecordList e) { return e.RecordPass == 0; });
                            for (int i = 0; i < recordLists.Count; i++)
                            {
                                if (attendanceInfos != null && attendanceInfos.Count > 0)
                                {
                                    List<AttendanceInfo> infos = attendanceInfos.FindAll(delegate (AttendanceInfo e) { return e.RecordID == recordLists[i].RecordID; });
                                    if (!(infos != null && infos.Count > 0))
                                    {
                                        VoucherInfo voucher = deviceDAL.QueryN71SPVoucher(deviceInfo.DeviceNO, recordLists[i].PersonID);
                                        if (voucher != null)
                                        {
                                            List<int> list = voucherDAL.QueryUserID(voucher.EmployeeNo);
                                            if (list != null && list.Count > 0)
                                            {
                                                DateTime dateTime = ConvertIntDateTime(recordLists[i].RecordTime);
                                                bool result = voucherDAL.InsertCheckRecord(list[0], recordLists[i].RecordID, deviceInfo.DeviceNO, dateTime);
                                                LogHelper.Log("同步考勤数据" + string.Format("EmployeeNo:{0},RecordID:{1},DeviceNO:{2},时间:{3}", voucher.EmployeeNo, recordLists[i].RecordID, deviceInfo.DeviceNO, dateTime.ToString("yyyy-MM-dd HH:mm:ss")));
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    VoucherInfo voucher = deviceDAL.QueryN71SPVoucher(deviceInfo.DeviceNO, recordLists[i].PersonID);
                                    if (voucher != null)
                                    {
                                        List<int> list = voucherDAL.QueryUserID(voucher.EmployeeNo);
                                        if (list != null && list.Count > 0)
                                        {
                                            DateTime dateTime = ConvertIntDateTime(recordLists[i].RecordTime);
                                            bool result = voucherDAL.InsertCheckRecord(list[0], recordLists[i].RecordID, deviceInfo.DeviceNO, dateTime);
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
            catch
            {

            }

            return "";
        }

        public NS71RecordReturn QueryN72SP(DeviceInfo deviceInfo, string starttime, string endtime, int offset, out int count, out int total)
        {
            NS71RecordReturn nS71RecordReturn = new NS71RecordReturn();
            try
            {
                string data = string.Empty;

                NS71Record record = new NS71Record();
                NS71RecordData nS71RecordEndData = new NS71RecordData();
                nS71RecordEndData.EndTime = ConvertDateTimeInt(Convert.ToDateTime(endtime).AddDays(1));
                nS71RecordEndData.StartTime = ConvertDateTimeInt(Convert.ToDateTime(starttime));
                nS71RecordEndData.Offset = offset;
                record.ParamsInfo = nS71RecordEndData;
                record.Token = deviceInfo.Token;
                data = JsonConvert.SerializeObject(record).Replace("ParamsInfo", "params");

                string re = N71SPHttpClientPost("http://" + deviceInfo.DeviceIP + "/api/faceId/queryRecords", data);
                nS71RecordReturn = JsonConvert.DeserializeObject<NS71RecordReturn>(re);
                if (nS71RecordReturn != null)
                {
                    if (nS71RecordReturn.result == 108)
                    {
                        DataDownLoad.UpdateRegisterFlag(deviceInfo.DeviceNO, false);
                        if (DataDownLoad.device_dic.ContainsKey(deviceInfo.DeviceNO))
                        {
                            DataDownLoad.device_dic.Remove(deviceInfo.DeviceNO);
                        }
                        DeviceDAL deviceDAL = new DeviceDAL();
                        deviceDAL.UpdateDeviceState(deviceInfo.ID, "离线");
                        count = 0;
                        total = 0;
                    }
                    else
                    {
                        count = nS71RecordReturn.Params.RecordCount;
                        total = nS71RecordReturn.Params.RecordTotal;
                    }
                }
                else
                {
                    count = 0;
                    total = 0;
                }

            }
            catch (Exception ex)
            {
                count = 0;
                total = 0;
                nS71RecordReturn = null;
            }
            return nS71RecordReturn;
        }

        public void N71SPDateSync(DeviceInfo deviceInfo)
        {
            try
            {
                string data = string.Empty;

                SetSystemTime systemTime = new SetSystemTime();
                SystemTimeData systemTimeData = new SystemTimeData();
                systemTimeData.DST = 0;
                systemTimeData.Date = DateTime.Now.ToString("yyyy-MM-dd");
                systemTimeData.Time = DateTime.Now.ToString("HH:mm:ss");
                systemTime.ParamsInfo = systemTimeData;
                systemTime.Token = deviceInfo.Token;
                data = JsonConvert.SerializeObject(systemTime).Replace("ParamsInfo", "params");
                LogHelper.Log(data);
                string re = N71SPHttpClientPost("http://" + deviceInfo.DeviceIP + "/api/system/setSystemTime", data);
                LogHelper.Log(re);
                SystemTimeReturn nS71RecordReturn = JsonConvert.DeserializeObject<SystemTimeReturn>(re);
            }
            catch
            {

            }
           
        }

        private long ConvertDateTimeInt(DateTime time)
        {
            return (time.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }

        public DateTime ConvertIntDateTime(long timestamp)
        {
            DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(timestamp);
            DateTime date = dateTimeOffset.LocalDateTime;
            return date;
        }

        public ResponseMessage SyncPerson()
        {
            ResponseMessage response = new ResponseMessage();
            try
            {
                DeviceDAL deviceDAL = new DeviceDAL();
                List<DeviceInfo> list = deviceDAL.QueryN71SPOffLine("在线");
                if (list != null && list.Count > 0)
                {
                    foreach (DeviceInfo deviceInfo in list)
                    {
                        N71SPQueryPeron(deviceInfo);
                    }
                }
            }
            catch (Exception ex)
            {

                response.errcode = 1;
                response.errmsg = "同步人员记录异常" + ex.ToString();
            }
            return response;
        }

        public string N71SPQueryPeron(DeviceInfo deviceInfo)
        {
            int offset = 0;
            int count = -1;
            int total = 0;
            int lastoffset = 0;
            while (lastoffset + count < total)
            {
                NS71PersonReturn infoReturn = QueryDeviceOwnerInfo(deviceInfo, offset, out count, out total);
                if (count == 0 && total == 0)
                {
                    break;
                }
                if (infoReturn != null && infoReturn.Params.PersonCount > 0)
                {
                    lastoffset = offset;

                    offset += 100;
                    List<PersonList> personLists = infoReturn.Params.Persons;
                    OwnerDAL ownerDAL = new OwnerDAL();
                    VoucherDAL voucherDAL = new VoucherDAL();
                    DeviceDAL deviceDAL = new DeviceDAL();
                    if (personLists != null && personLists.Count > 0)
                    {
                        foreach (PersonList personList in personLists)
                        {
                            LogHelper.Log(JsonConvert.SerializeObject(personList));
                            OwnerInfo ownerInfo = ownerDAL.QueryOwnerInfo(personList.PersonID);
                            if (ownerInfo == null)
                            {
                                OwnerInfo owner = new OwnerInfo();
                                owner.OwnerName = personList.PersonName;
                                owner.CardNO = personList.ICCardID;
                                owner.EmployeeNo = personList.PersonID;
                                owner.OwnerType = 1;
                                owner.RoomID = 3;
                                owner.ParentID = 0;
                                owner.VirtualCard = 0;
                                owner.projectID = 1;
                                int id = ownerDAL.AddOwner_1(owner);

                                VoucherInfo voucherInfo = new VoucherInfo();
                                voucherInfo.OwnerID = id;
                                voucherInfo.EffectiveStarttime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                voucherInfo.EffectiveEndtime = Convert.ToDateTime("2106-02-07 14:28:15").ToString("yyyy-MM-dd HH:mm:ss");
                                voucherInfo.DeviceID = deviceInfo.ID;
                                voucherDAL.SyncVoucher(voucherInfo);
                            }
                            else
                            {
                                List<VoucherInfo> voucherInfos = voucherDAL.QueryN71SPVoucher(deviceInfo.ID, ownerInfo.ID);
                                if (!(voucherInfos != null && voucherInfos.Count > 0))
                                {
                                    if (voucherDAL.UpdateN71SPOwnerInfo(personList.ICCardID, ownerInfo.ID))
                                    {
                                        VoucherInfo voucherInfo = new VoucherInfo();
                                        voucherInfo.OwnerID = ownerInfo.ID;
                                        voucherInfo.EffectiveStarttime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                        voucherInfo.EffectiveEndtime = Convert.ToDateTime("2106-02-07 14:28:15").ToString("yyyy-MM-dd HH:mm:ss");
                                        voucherInfo.DeviceID = deviceInfo.ID;
                                        voucherDAL.SyncVoucher(voucherInfo);
                                    }
                                }

                            }
                        }

                    }

                }
            }

            return "";
        }

        public NS71PersonReturn QueryDeviceOwnerInfo(DeviceInfo deviceInfo, int offset, out int count, out int total)
        {
            NS71PersonReturn infoReturn = new NS71PersonReturn();
            try
            {
                NS71PersonQuery nS71PersonQuery = new NS71PersonQuery();
                NS71PersonQueryData nS71PersonQueryData = new NS71PersonQueryData();
                nS71PersonQuery.Token = deviceInfo.Token;
                nS71PersonQueryData.Offset = offset;
                nS71PersonQuery.ParamsInfo = nS71PersonQueryData;
                string data = JsonConvert.SerializeObject(nS71PersonQuery).Replace("ParamsInfo", "params");
                string re = N71SPHttpClientPost("http://" + deviceInfo.DeviceIP + "/api/person/loadPersonsByDepartID", data);
                infoReturn = JsonConvert.DeserializeObject<NS71PersonReturn>(re);
                if (infoReturn != null)
                {
                    if (infoReturn.result == 108)
                    {
                        DataDownLoad.UpdateRegisterFlag(deviceInfo.DeviceNO, false);
                        if (DataDownLoad.device_dic.ContainsKey(deviceInfo.DeviceNO))
                        {
                            DataDownLoad.device_dic.Remove(deviceInfo.DeviceNO);
                        }
                        DeviceDAL deviceDAL = new DeviceDAL();
                        deviceDAL.UpdateDeviceState(deviceInfo.ID, "离线");
                        count = 0;
                        total = 0;
                    }
                    else
                    {
                        count = infoReturn.Params.PersonCount;
                        total = infoReturn.Params.PersonTotal;
                    }

                }
                else
                {
                    count = 0;
                    total = 0;
                }
            }
            catch (Exception ex)
            {
                count = 0;
                total = 0;
            }
            return infoReturn;
        }

       

    }
}
